package com.lms.util.WeixinUtil;

import com.alibaba.fastjson.JSONObject;
import com.lms.dao.BaseDao;
import com.lms.dao.weixin.WeixinDao;
import com.lms.dao.weixin.WeixinDaoImpl;
import com.lms.util.WeixinUtil.pojo.WeixinAccess_token;
import com.lms.util.WeixinUtil.pojo.WeixinTicket;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;


public class WeixinUtil {
    private static Connection connection;
    private static WeixinDao weixinDao=new WeixinDaoImpl();
    /**
     * 排序方法
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String sort(String token, String timestamp, String nonce) {
        String[] strArray = { token, timestamp, nonce };
        Arrays.sort(strArray);

        StringBuilder sbuilder = new StringBuilder();
        for (String str : strArray) {
            sbuilder.append(str);
        }

        return sbuilder.toString();
    }
    /*SHA1编码校验*/
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    /*模板消息json排版*/
    public static JSONObject getValue(String value) {
        JSONObject json = new JSONObject();
        json.put("value", value);
        json.put("color", "#173177");
        return json;
    }
    public static JSONObject getValue(String value,String color) {
        JSONObject json = new JSONObject();
        json.put("value", value);
        json.put("color", color);
        return json;
    }

    /*获取access_token*/
    public static String getAccess_token() {
        connection = BaseDao.getConnection();
        WeixinAccess_token access_token = null;
        String res=null;
        try {
            access_token = weixinDao.getAccess_token(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (access_token!=null){
            if (access_token.getAccess_token() == null){
                //还未获取access_token
                WeixinAccess_token newAccess_token = getAccess_tokenImpl();//获取access_token
                if (newAccess_token!=null){//持久化access_token
                    try {
                        weixinDao.setAccess_token(connection,newAccess_token);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }finally {
                        BaseDao.closeResource(connection,null,null);
                    }
                    res=newAccess_token.getAccess_token();
                }
                return res;

            }else {
                long lastDate = access_token.getAccess_token_createTime();
                long nowDate = System.currentTimeMillis();
                if (nowDate-lastDate>59*60*1000){//access_token已过期
                    WeixinAccess_token newAccess_token = getAccess_tokenImpl();
                    if (newAccess_token!=null){//持久化access_token
                        try {
                            weixinDao.setAccess_token(connection,newAccess_token);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }finally {
                            BaseDao.closeResource(connection,null,null);
                        }
                        res=newAccess_token.getAccess_token();
                    }
                    return res;
                }else {
                    return access_token.getAccess_token();
                }
            }
        }else
            return null;
    }
    private static WeixinAccess_token getAccess_tokenImpl(){
        String api="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WeixinConstants.APPID+"&secret="+WeixinConstants.APPSECRET;
        StringBuffer buffer = new StringBuffer();
        WeixinAccess_token weixinAccess_token=null;
        try{
            /*核心方法：后端向接口发送请求*/
            URL url = new URL(api);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            httpUrlConn.disconnect();

            //将获取到的access_token解析
            JSONObject json = JSONObject.parseObject(buffer.toString());
            String access_token = (String)json.get("access_token");
            weixinAccess_token = new WeixinAccess_token();
            weixinAccess_token.setAccess_token(access_token);
            weixinAccess_token.setAccess_token_createTime(System.currentTimeMillis());
        }catch (Exception e){
            e.printStackTrace();
        }
        return weixinAccess_token;
    }
    /*获取ticket*/
    public static WeixinTicket getTicket(String access_token, String userCode) {
        WeixinTicket weixinTicket=null;
        StringBuffer buffer=new StringBuffer();
        String api="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+access_token;
        try {
            URL url = new URL(api);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.connect();

            // 当有数据需要提交时
            /*使用永久二维码*/
            String jsonStr="{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+userCode+"\"}}}";
            OutputStream outputStream = httpUrlConn.getOutputStream();
            // 注意编码格式，防止中文乱码
            outputStream.write(jsonStr.getBytes("UTF-8"));
            outputStream.close();

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            httpUrlConn.disconnect();

            //将获取到的ticket解析
            JSONObject json = JSONObject.parseObject(buffer.toString());
            weixinTicket = new WeixinTicket();
            weixinTicket.setTicket((String) json.get("ticket"));
            weixinTicket.setExpire_seconds((Integer)json.get("expire_seconds"));
            weixinTicket.setUrl((String)json.get("url"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return weixinTicket;
    }
}
